package pers.cyril.jdb.client.command.handler;

import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 说点什么吧
 *
 * @author Wang Cyril
 * @date 2024/5/29 19:35
 */
public class CommandHandlerManager {

    private static Map<Class<?>,CommandHandler> map = new ConcurrentHashMap<>();

    static {
        String packageName = CommandHandler.class.getPackage().getName();
        Reflections reflection = new Reflections(packageName,new SubTypesScanner());

        Set<Class<? extends CommandHandler>> handlers = reflection.getSubTypesOf(CommandHandler.class);
        for (Class<? extends CommandHandler> handler : handlers) {
            Type[] types = handler.getGenericInterfaces();
            for (Type type : types) {
                if (!(type instanceof ParameterizedType)) {
                    continue;
                }
                ParameterizedType parameterizedType = (ParameterizedType) type;
                Type rawType = parameterizedType.getRawType();
                if (rawType != CommandHandler.class) {
                    continue;
                }

                // 获取 List 接口的泛型参数类型
                Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
                Type argumentType = actualTypeArguments[0];
                try {
                    map.put((Class<?>)argumentType,handler.newInstance());
                } catch (InstantiationException | IllegalAccessException e) {
                    throw new RuntimeException(e);
                }

            }

        }
    }

    public static <T> CommandHandler<T> getHandler(Class<T> commandType){
        return map.get(commandType);
    }
}
